package com.manage.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.manage.config.model.Config;
import com.manage.user.model.Operation;
import com.manage.user.model.User;
import com.manage.util.SystemUtil;

public class AccessFilter
		implements Filter {

	static final Logger logger = Logger.getLogger(AccessFilter.class);

	protected FilterConfig config;

	public void destroy() {
	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain filterChain)
			throws IOException, ServletException {
		if (SystemUtil.isDebug()) {
			filterChain.doFilter(arg0, arg1);
		} else {
			HttpServletRequest request = (HttpServletRequest) arg0;
			HttpServletResponse response = (HttpServletResponse) arg1;
			String url = request.getRequestURI();
			logger.info("AccessFilter start url " + url);
			Object obj = request.getSession().getAttribute(Config.USER_SESSION);
			if (url.indexOf("login") != -1) {
				request.getSession().removeAttribute(Config.USER_SESSION);
				filterChain.doFilter(arg0, arg1);
			} else {
				if (obj == null) {
					response.sendRedirect("/login.html");
				} else {
					User user = (User) obj;
					List<Operation> operations = user.getOperations();
					boolean flag = false;
					for (Operation operation : operations) {
						if (operation.getOperationUrl().indexOf(url) > -1) {
							flag = true;
							filterChain.doFilter(arg0, arg1);
							break;
						}
					}
					if (!flag) {
						logger.info("该用户没有权限访问 URL: " + url);
						response.sendRedirect("/login.html");
					}
				}
			}
		}
	}

	public void init(FilterConfig arg0) throws ServletException {
		this.config = arg0;
	}
}
